<?php
session_start ();
if (! isset ( $_SESSION ['id'] ) or ! isset ( $_POST ['tname'] ))
	exit ();
require_once 'common.inc';
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';

// 检查权限
if ($_SESSION ['aboutme'] != '总部用户') {
	$bRight = true;
	switch ($_POST ['tname']) {
		case 'customer' :
		case 'logic' :
		case 'user' :
		case 'management' :
		case 'item' :
		case 'input' :
		case 'output' :
			$bRight = false;
			break;
	}
	if (! $bRight) {
		echo ("{success:false,msg:\"导入未授权的数据！\"}");
		exit ();
	}
}

// 上传文件
$inputFileName = "tmp/" . $_POST ['tname'] . ".xls";
if (! @move_uploaded_file ( $_FILES ['userfile'] ['tmp_name'], $inputFileName )) {
	echo ("{success:false,msg:\"上传失败！\"}");
	exit ();
}

// 开始导入
$inputFileType = PHPExcel_IOFactory::identify ( $inputFileName );
if (strpos ( $inputFileType, "Excel" ) === false) {
	echo ("{success:false,msg:\"不是一个有效的excel文件！\"}");
	exit ();
}
$objReader = PHPExcel_IOFactory::createReader ( $inputFileType );
$objPHPExcel = $objReader->load ( $inputFileName );
$sheetData = $objPHPExcel->getActiveSheet ()->toArray ( null, true, true, false );

$str1 = "";
$str2 = "";
$sql = "";
// 表头
for($i = 0; $i < count ( $sheetData [0] ); $i ++) {
	if (preg_match ( '/(?<=\()[\w]+(?=\))/i', $sheetData [0] [$i], $matches ))
		$str1 .= strtolower ( $matches [0] ) . ",";
	else
		$str1 = strtolower ( $sheetData [0] [$i] ) . ",";
}
// 表内容
for($i = 1; $i < count ( $sheetData ); $i ++) {
	$str2 .= "(";
	for($j = 0; $j < count ( $sheetData [$i] ); $j ++) {
		if (preg_match ( '/^[\d]{4}-[\d]{2}-[\d]{2} [0]{2}:[0]{2}:[0]{2}$/', $sheetData [$i] [$j], $matches ))
			$str2 .= "'" . str_replace ( ' 00:00:00', '', $matches [0] ) . "',";
		else
			$str2 .= "'" . addslashes ( $sheetData [$i] [$j] ) . "',";
	}
	$str2 = substr ( $str2, 0, - 1 ) . "),";
}
$sql = "INSERT INTO " . $_POST ['tname'] . " (" . substr ( $str1, 0, - 1 ) . ") VALUES " . substr ( $str2, 0, - 1 );

$result = execSQL ( $sql );
if ($result)
	echo ("{success:true}");
else
	echo ("{success:false,msg:\"" . mysql_error () . "\"}");
	
	// 删除临时文件
unlink ( $inputFileName );
?>

